<?php

namespace mpend\models;

use Yii;
use Exception;
use common\helpers\FileHelper;
use common\helpers\IpHelper;
use common\models\Attachment;
use yii\web\UploadedFile;
use Imagine\Exception\NotSupportedException;

/**
 * 图片上传模型
 * UploadImage is the model behind the upload form.
 */
class UploadImage extends \common\base\Model {

    use \common\traits\Constants;

    const SCOPE_DEFAULT = 'default';
    const SCOPE_USER = 'user';
    const SCOPE_AUTHENT = 'authent';
    const SCOPE_ACTIVITY = 'activity';

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id = 0;

    /**
     * @name $scope
     * @var string 应用范围
     */
    public $scope = 'default';

    /**
     * @name $imageFile 待上传文件
     * @var \yii\web\UploadedFile file attribute
     */
    public $imageFile = null;

    /**
     * @name $channel
     * @var string 上传通道，支持通道阿里云OSS:、服务器SFTP
     */
    public $channel = 'OSS';

    /**
     * @name $cut
     * @var integer 是否启用图片压缩
     */
    public $cut = 0;

    /**
     * @name $uploadPath
     * @var string 上传根目录别名
     */
    public $uploadPath = '@uploads';

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            [['imageFile'], 'required'],
            [['user_id'], 'integer'],
            ['scope', 'in', 'range' => static::getConstants(), 'message' => '{attribute}不在允许范围内'],
            [
                'imageFile',
                'file',
                'mimeTypes' => ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'user_id' => '用户ID',
            'scope' => '应用场景',
            'imageFile' => '文件',
        ];
    }

    public function upload() {
        if (!$this->validate()) {
            $this->validateError('上传校验失败');
        }
        $file = $this->imageFile;
        if (!($file instanceof UploadedFile)) {
            $this->validateError('上传文件校验失败');
        }
        try {
            $size = getimagesize($file->tempName);
            if ($size === false) {
                throw new NotSupportedException('文件格式错误，请上传图片文件');
            }
            list($width, $height, $type) = $size;
        } catch (Exception $exc) {
            $this->validateError($exc->getMessage());
        }
        if (!$type) {
            $this->validateError('图片文件类型错误');
        }
        $extension = image_type_to_extension($type);
        if (!$extension) {
            $this->validateError($extension . '图片文件格式错误');
        }
        $relativeDir = '/attachments/' . $this->scope . '/' . date('Ym/d') . '/';
        $absoluteDir = Yii::getAlias($this->uploadPath . $relativeDir);
        FileHelper::createDirectory($absoluteDir);
        $filename = FileHelper::buildUploadFileName($extension);
        $file->saveAs($absoluteDir . $filename);
        $relativePath = $relativeDir . $filename;
        if ($file->getHasError()) {
            $this->dumpError('文件保存失败', $file->error);
        }
        if (YII_ENV_PROD) {
            try {
                /* @var $oss \common\components\aliyun\AliyunOSS */
                $oss = Yii::$app->alioss;
                $oss->uploadFile(ltrim($relativePath, '/'), $absoluteDir . $filename, 'public-read');
            } catch (Exception $e) {
                return $this->dumpError($e->getMessage());
            }
        }
        $attachs = new Attachment();
        $attachs->attributes = [
            'user_id' => $this->user_id,
            'path' => $relativePath,
            'original_name' => $file->name,
            'channel' => $this->channel,
            'size' => $file->size,
            'isimage' => 1,
            'width' => $width,
            'height' => $height,
            'ip' => IpHelper::ip(),
        ];
        $attachs->generateToken();
        if (!$attachs->save()) {
            return $attachs->dumpError();
        }
        return $attachs->toArray();
    }

}
